package com.gzw.scm.wuyong;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.BDAdapter;
import com.gzw.scm.base.NewBaseActivity;
import com.gzw.scm.bean.BDInfo;
import com.gzw.scm.bean.CodeInfo;
import com.gzw.scm.bean.SCBDInfo;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/7/31.
 */

public class BuBangActivity extends NewBaseActivity{
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private Intent intent;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll;
    private boolean isCheck = false;
    private DBManager dbManager;
    private BDAdapter bdAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String dataType;
    private BDInfo bdInfo;
    private List<BDInfo> ls_bdInfo,lsbh;
    private List<SCBDInfo> ls_scbd;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_bd);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head2).findViewById(R.id.tv_selectAll);
    }

    @Override
    protected void initData() {
        mContext = this;
        intent = getIntent();

        toolbar.setTitle("箱码补绑");
        dataType="rdcbb";
        setSupportActionBar(toolbar);

        dbManager=new DBManager(mContext);
        bdInfo=new BDInfo();
        ls_bdInfo=new ArrayList<>();

        /**
         * 刷新框架
         * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
        setData();
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    senddata();
                    break;
                case R.id.btn_delete:
                    deleteZzxbh();
                    break;
                case R.id.tv_selectAll:
                    if (ls_bdInfo != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bdInfo.size(); i++) {
                                BDAdapter.getIsSelected().put(i, true);
                            }
                            bdAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bdInfo.size(); i++) {
                                if (BDAdapter.getIsSelected().get(i)) {
                                    BDAdapter.getIsSelected().put(i, false);
                                }
                            }
                            bdAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    }


    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        panduan(code);
        return code;
    };

    /**
     * 判断扫描条码类型
     * */
    private void panduan(String message){
        if(message.indexOf("SSID")>0){
            CodeInfo codeInfo = JsonUtil.getPerson(message, CodeInfo.class);
            String code = codeInfo.getNO();
            savecode("0",code);
        }else{
            if(message.substring(0,1).equals("P")&&message.length()==11){
                savecode("1",message);
            }else{
                T.showShort(mContext,"该条码不是WMS系统的箱号");
            }
        }
    }

    /**
     * 保存扫描二维码和一维码
     * 0-二维码，1-一维码
     * */
    private void savecode(String type,String code){
        List<BDInfo> ls_info = dbManager.SelectBDInfo(MyApplication.getUserInfo().getDid(),dataType);
        if(ls_info.size()>0){
            int i = ls_info.size()-1;
            if(ls_info.get(i).getXm()==null||ls_info.get(i).getZzxbh()==null){
                bdInfo = ls_info.get(i);
            }
        }

        if(type.equals("0")){
            if(dbManager.isBdCode2(code,MyApplication.getUserInfo().getDid(),dataType,"1")){
                T.showShort(mContext,"该周转箱编号已扫描");
                return;
            }

            if(dbManager.isBdCode2(code,MyApplication.getUserInfo().getDid(),dataType,"0")){
                BDInfo bdInfo1 = new BDInfo();
                bdInfo1.setZzxbh(code);
                dbManager.deleteByzzx(bdInfo1,MyApplication.getUserInfo().getDid(), dataType);

                bdInfo.setZzxbh(code);
                dbManager.addBdinfo(bdInfo, dataType, MyApplication.getUserInfo().getDid(), "1");
                setData();

            }else {

                if (bdInfo.getZzxbh() == null) {
                    if (bdInfo.getXm() != null) {
                        dbManager.deleteByxm(bdInfo, MyApplication.getUserInfo().getDid(), dataType);
                    }
                    bdInfo.setZzxbh(code);
                    dbManager.addBdinfo(bdInfo, dataType, MyApplication.getUserInfo().getDid(), "1");
                    setData();
                } else {
                    T.showShort(mContext, "请扫描箱标签一维码");
                }
            }
        }else if(type.equals("1")){

//            if(bdInfo.getZzxbh()==null){
//                T.showShort(mContext,"请先扫描二维码");
//                return;
//            }

            if(dbManager.isBdCode1(code,MyApplication.getUserInfo().getDid(),dataType)){
                T.showShort(mContext,"该箱码已扫描");
                return;
            }

            if(bdInfo.getXm()==null){
                if(bdInfo.getZzxbh()!=null){
                    dbManager.deleteByzzx(bdInfo ,MyApplication.getUserInfo().getDid(),dataType);
                }
                bdInfo.setXm(code);
                dbManager.addBdinfo(bdInfo,dataType ,MyApplication.getUserInfo().getDid(),"1");
                setData();
            }else {
                T.showShort(mContext,"请扫描周转箱二维码");
            }
        }

        if(bdInfo.getZzxbh()!=null&&bdInfo.getXm()!=null){
            bdInfo=new BDInfo();
        }

    }

    private void setData(){
        ls_bdInfo.clear();
        ls_bdInfo =new ArrayList<>();
        List<BDInfo> ls_bd = dbManager.SelectBDInfo(MyApplication.getUserInfo().getDid(),dataType);

        if(ls_bd==null){
            return;
        }else {
            ls_bdInfo.addAll(ls_bd);
        }
        if(ls_bdInfo==null){
            return;
        }

        bdAdapter = new BDAdapter(ls_bdInfo,mContext);
        mRecyclerView.setAdapter(bdAdapter);

        bdAdapter.setOnRecyclerViewListener(new BDAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if(BDAdapter.getIsSelected().get(position)==true){
                    BDAdapter.getIsSelected().put(position, false);
                    bdAdapter.notifyDataSetChanged();
                }else{
                    BDAdapter.getIsSelected().put(position, true);
                    bdAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });
    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
        List<BDInfo> lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bdInfo.size(); i++) {
            if (bdAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bdInfo.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的信息!");
        }else {
            for (BDInfo bdInfo1 : lsbh) {
                if (bdInfo1.getXm() == null && bdInfo1.getZzxbh() != null) {
                    bdInfo=new BDInfo();
                }
            }
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<BDInfo> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
                dbManager.deleteBDInfo(ls_bh,MyApplication.getUserInfo().getDid(),dataType);
                setData();

        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传绑定信息
     * */
    private void senddata() {
        lsbh = new ArrayList<>();
        for (int i = 0; i < ls_bdInfo.size(); i++) {
            if (bdAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bdInfo.get(i));
            }
        }

        if (lsbh.size() == 0) {
            T.showShort(mContext, "请先选择绑定信息");
        } else {
            ls_scbd = new ArrayList<>();
            for (BDInfo bdInfo : lsbh) {
                if (bdInfo.getXm() == null || bdInfo.getZzxbh() == null) {
                    T.showShort(mContext, "请完成周转箱编号和箱码的对应扫描");
                    return;
                } else {
                    SCBDInfo scbdInfo = new SCBDInfo();
                    scbdInfo.setBelongid(String.valueOf(MyApplication.getUserInfo().getBelongId()));
                    scbdInfo.setDept(String.valueOf(MyApplication.getUserInfo().getDid()));
                    scbdInfo.setTboxid(bdInfo.getZzxbh());
                    scbdInfo.setOrdnoid(bdInfo.getXm());
                    ls_scbd.add(scbdInfo);
                }
            }

            String json = JsonUtil.toJson(ls_scbd);
            SendBBTask sendTask = new SendBBTask();
            sendTask.execute(json);
        }
    }
    /**
     * 上传的数据请求
     * 补绑
     * */

    public class SendBBTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {

            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do", "Complement"),"strJson="+params[0]);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (result == null || result.length() == 0) {
//                T.showShort(mContext, "连接服务器异常");
                showAlertDialog("连接异常");
                return;
            }

            List<BDInfo> ls_bd=new ArrayList<>();
            for(SCBDInfo scbdInfo:ls_scbd){
                BDInfo bdInfo = new BDInfo();
                bdInfo.setZzxbh(scbdInfo.getTboxid());
                bdInfo.setXm(scbdInfo.getOrdnoid());
                bdInfo.setZt("1");
                ls_bd.add(bdInfo);
            }

            String ERRStr = "",ERR1Str = "",ERR2Str = "",ERR3Str = "",ERR4Str = "",ERR5Str = "";
            if(JsonUtil.getMsg(result,"ERR").toString().length()!=0){
                //周转箱绑定失败
                String ERRstring = JsonUtil.getMsg(result,"ERR").toString();
                List<String> ls_str = JsonUtil.getPersons(ERRstring, new TypeToken<List<String>>() {
                }.getType());
                ls_str.remove(0);
                for(String string:ls_str){
                    for(int i=0;i<ls_bd.size();i++){
                        if(ls_bd.get(i).getZzxbh().equals(string)){
                            ls_bd.remove(i);
                        }
                    }
                }
                ERRStr = "周转箱"+ ls_str.toString()+"绑定失败";
            }
            if(result.indexOf("ERR1")>=0){
                //周转箱绑定失败
                String ERRstring = JsonUtil.getMsg(result, "ERR1").toString();
                List<String> ls_str = JsonUtil.getPersons(ERRstring, new TypeToken<List<String>>() {
                }.getType());
                ls_str.remove(0);
                for(String string:ls_str){
                    for(int i=0;i<ls_bd.size();i++){
                        if(ls_bd.get(i).getZzxbh().equals(string)){
                            ls_bd.remove(i);
                        }
                    }
                }
                ERR1Str = "周转箱"+ ls_str.toString()+"已绑定";
            }

            if(result.indexOf("ERR2")>=0){
                //周转箱绑定失败
                String ERRstring = JsonUtil.getMsg(result, "ERR2").toString();
                List<String> ls_str = JsonUtil.getPersons(ERRstring, new TypeToken<List<String>>() {
                }.getType());
                ls_str.remove(0);
                for(String string:ls_str){
                    for(int i=0;i<ls_bd.size();i++){
                        if(ls_bd.get(i).getXm().equals(string)){
                            ls_bd.remove(i);
                        }
                    }
                }
                ERR2Str = "箱号"+ ls_str.toString()+"已绑定";
            }

            if(result.indexOf("ERR3")>=0){
                //周转箱绑定失败
                String ERRstring = JsonUtil.getMsg(result, "ERR3").toString();
                List<String> ls_str = JsonUtil.getPersons(ERRstring, new TypeToken<List<String>>() {
                }.getType());
                ls_str.remove(0);
                for(String string:ls_str){
                    for(int i=0;i<ls_bd.size();i++){
                        if(ls_bd.get(i).getXm().equals(string)){
                            ls_bd.remove(i);
                        }
                    }
                    ERR3Str = "箱号"+ ls_str.toString()+"不在系统中";
                }
            }

            if(result.indexOf("ERR4")>=0) {
                //周转箱绑定失败
                String ERRstring = JsonUtil.getMsg(result, "ERR4").toString();
                List<String> ls_str = JsonUtil.getPersons(ERRstring, new TypeToken<List<String>>() {
                }.getType());
                ls_str.remove(0);
                for (String string : ls_str) {
                    for (int i = 0; i < ls_bd.size(); i++) {
                        if (ls_bd.get(i).getXm().equals(string)) {
                            ls_bd.remove(i);
                        }
                    }
                    ERR4Str = "箱号" + ls_str.toString() + "对应客户不在本系统中";
                }
            }

            if(result.indexOf("ERR5")>=0) {
                //周转箱绑定失败
                String ERRstring = JsonUtil.getMsg(result, "ERR5").toString();
                List<String> ls_str = JsonUtil.getPersons(ERRstring, new TypeToken<List<String>>() {
                }.getType());
                ls_str.remove(0);
                for (String string : ls_str) {
                    for (int i = 0; i < ls_bd.size(); i++) {
                        if (ls_bd.get(i).getXm().equals(string)) {
                            ls_bd.remove(i);
                        }
                    }
                    ERR5Str = "箱号" + ls_str.toString() + "状态异常";
                }
            }

            String successNum =JsonUtil.getMsg(result, "num").toString();
            String str = ERRStr+ERR1Str+ERR2Str+ERR3Str+ERR4Str+ERR5Str;
            if(str.equals("")){
                showAlertDialog("绑定成功"+successNum+"个周转箱");
            }else{
                showAlertDialog("绑定成功"+successNum+"个周转箱,"+str);
            }
            dbManager.deleteBDInfo(ls_bd,MyApplication.getUserInfo().getDid(),dataType);
            setData();

        }
    }

    class jgInfo{
        private String result;

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }
    }

}